<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发现时间" prop="discoveryTime">
        <el-date-picker
          clearable
          v-model="queryParams.discoveryTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发现时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="整改时间" prop="rectificationTime">
        <el-date-picker
          clearable
          v-model="queryParams.rectificationTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择整改时间"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 0 未整改 1 已整改 2 已复核 -->
      <el-form-item label="任务状态 " prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态 0 未整改 1 已整改 2 已复核"
          clearable
        >
          <el-option
            v-for="dict in dict.type.bus_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:repair:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:repair:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:repair:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:repair:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="repairList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="100"
        align="center"
        v-if="getColumn('index')"
      >
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="主键" align="center" prop="id" v-if="getColumn('id')" /> -->
      <el-table-column
        label="任务编号"
        align="center"
        prop="taskCode"
        v-if="getColumn('taskCode')"
      />
      <el-table-column
        label="任务名称"
        align="center"
        prop="taskName"
        v-if="getColumn('taskName')"
      />
      <el-table-column
        label="详细地址"
        align="center"
        prop="address"
        v-if="getColumn('address')"
      />
      <el-table-column
        label="发现时间"
        align="center"
        prop="discoveryTime"
        width="180"
        v-if="getColumn('discoveryTime')"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.discoveryTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="整改前照片"
        align="center"
        prop="taskImage"
        width="100"
        v-if="getColumn('taskImage')"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.taskImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="整改时间"
        align="center"
        prop="rectificationTime"
        width="180"
        v-if="getColumn('rectificationTime')"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.rectificationTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="整改后照片"
        align="center"
        prop="rectificationImage"
        width="100"
        v-if="getColumn('rectificationImage')"
      >
        <template slot-scope="scope">
          <image-preview
            :src="scope.row.rectificationImage"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="复核时间"
        align="center"
        prop="checkTime"
        width="180"
        v-if="getColumn('checkTime')"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.checkTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="复核后照片"
        align="center"
        prop="checkImage"
        width="100"
        v-if="getColumn('checkImage')"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.checkImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="任务状态 0 未整改 1 已整改 2 已复核"
        align="center"
        prop="taskStatus"
        v-if="getColumn('taskStatus')"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.bus_task_status"
            :value="scope.row.taskStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="repairDesc"
        v-if="getColumn('repairDesc')"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="getColumn('operate')"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:repair:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:repair:remove']"
            >删除</el-button
          >

          <!-- 加个下达任务的功能  添加权限字符串 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-position"
            @click="Taskdispatch(scope.row)"
            v-hasPermi="['business:repair:dispatch']"
            >派遣</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination 
      v-show="total > 0"
      :total="total"
      :pageSizes="pageSizes"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="发现时间" prop="discoveryTime">
          <el-date-picker
            clearable
            v-model="form.discoveryTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发现时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="整改前照片" prop="taskImage">
          <image-upload v-model="form.taskImage" />
        </el-form-item>

        <!-- 添加权限 -->

        <el-form-item
          v-if="form.taskStatus == 1 || form.taskStatus == 2"
          label="整改时间"
          prop="rectificationTime"
        >
          <el-date-picker
            clearable
            v-model="form.rectificationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择整改时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          v-if="form.taskStatus == 1 || form.taskStatus == 2"
          label="整改后照片"
          prop="rectificationImage"
        >
          <image-upload v-model="form.rectificationImage" />
        </el-form-item>

        <el-form-item
          v-if="form.taskStatus == 2"
          label="复核时间"
          prop="checkTime"
        >
          <el-date-picker
            clearable
            v-model="form.checkTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择复核时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          v-if="form.taskStatus == 2"
          label="复核后照片"
          prop="checkImage"
        >
          <image-upload v-model="form.checkImage" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 派遣任务 -->
    <el-dialog
      title="派遣任务"
      :visible.sync="openTask"
      width="700px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span style="font-style: italic">任务信息 :</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务名称" prop="taskName">
                <el-input
                  v-model="form.taskName"
                  placeholder="请输入任务名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务编号" prop="taskCode">
                <el-input
                  v-model="form.taskCode"
                  placeholder="请输入任务编号"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="详细地址" prop="address">
                <el-input
                  v-model="form.address"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12"
              ><el-form-item label="发现时间" prop="discoveryTime">
                <el-date-picker
                  clearable
                  v-model="form.discoveryTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择发现时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="整改前照片" prop="taskImage">
                <image-upload v-model="form.taskImage" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="整改时间" prop="rectificationTime">
                <el-date-picker
                  clearable
                  v-model="form.rectificationTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择整改时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 派遣员工 -->
        <el-card shadow="hover" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span style="font-style: italic">员工信息 :</span>
            </div>
          </template>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAddPerson"
                >添加</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="Delete" @click="handleDeletePerson"
                >删除</el-button
              >
            </el-col>
          </el-row>

          <el-table
            :data="personList"
            :row-class-name="rowPersonIndex"
            @selection-change="handlePersonSelectionChange"
            ref="person"
          >
            <el-table-column type="selection" width="50" align="center" />

            <el-table-column
              label="序号"
              align="center"
              prop="index"
              width="50"
            />

            <el-table-column label="选择员工" prop="id" width="150">
              <template #default="scope">
                <el-select
                  v-model="scope.row.id"
                  @change="fillPersonInfo(scope.$index, scope.row.id)"
                  placeholder="请选择员工"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in repairPersonList"
                    :key="item.id"
                    :label="item.personName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="联系电话" prop="personPhone" width="150">
              <template #default="scope">
                <el-input
                  v-model="scope.row.personPhone"
                  placeholder="请输入联系电话"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="上岗证编号"
              prop="certificateId"
              width="150"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.certificateId"
                  placeholder="请输入上岗证编号"
                />
              </template>
            </el-table-column>

            <el-table-column label="班组" prop="teamId" width="150">
              <template #default="scope">
                <dict-tag
                  :options="dict.type.bus_person_group"
                  :value="scope.row.teamId"
                />
              </template>
            </el-table-column>

            <el-table-column label="岗位" prop="postId" width="150">
              <template #default="scope">
                <dict-tag
                  :options="dict.type.bus_person_post"
                  :value="scope.row.postId"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="AddTask()"
            v-hasPermi="['business:repair:dispatch']"
            >确 定</el-button
          >
          <el-button @click="closeopenTask()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRepair,
  getRepair,
  delRepair,
  addRepair,
  updateRepair,
  dispatchTask,
} from "@/api/business/repair";
import { mapGetters } from "vuex";
import { getPostPerson } from "@/api/business/person";
import { getJob, updateJob, changeJobStatus } from "@/api/monitor/job";
export default {
  name: "Repair",
  dicts: ["bus_task_status", "bus_person_group", "bus_person_post"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 派遣员工列表
      personList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修任务表格数据
      repairList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 派遣页面
      openTask: false,
      // 子表选中的数据
      checkedPerson: [],
      // 所有维修部员工列表
      repairPersonList: [],
      // 定时任务
      job: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        taskName: null,
        address: null,
        discoveryTime: null,
        rectificationTime: null,
        taskStatus: null,
        repairDesc: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        taskStatus: [
          {
            required: true,
            message: "任务状态 0 未整改 1 已整改 2 已复核不能为空",
            trigger: "change",
          },
        ],
      },
      // 列信息
      columns: [
        { key: "index", label: `序号`, visible: true },
        { key: "id", label: "主键", visible: true },
        { key: "taskCode", label: "任务编号", visible: true },
        { key: "taskName", label: "任务名称", visible: true },
        { key: "address", label: "详细地址", visible: true },
        { key: "discoveryTime", label: "发现时间", visible: true },
        { key: "taskImage", label: "整改前照片", visible: true },
        { key: "rectificationTime", label: "整改时间", visible: true },
        { key: "rectificationImage", label: "整改后照片", visible: true },
        { key: "checkTime", label: "复核时间", visible: true },
        { key: "checkImage", label: "复核后照片", visible: true },
        {
          key: "taskStatus",
          label: "任务状态 0 未整改 1 已整改 2 已复核",
          visible: true,
        },
        { key: "repairDesc", label: "备注", visible: true },
        { key: "operate", label: `操作`, visible: true },
      ],
      // 分页参数
      pageSizes: [10, 50, 100, 500, 1000],
    };
  },
  created() {
    this.getList();
    // this.getJob();
  },
  mounted() {
    this.getJob();
  },
  computed: {
    ...mapGetters(["id"]),
  },
  methods: {
    /** 查询维修任务列表 */
    getList() {
      this.loading = true;
      listRepair(this.queryParams).then((response) => {
        this.repairList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createUser: null,
        createBy: null,
        createTime: null,
        updateUser: null,
        updateBy: null,
        updateTime: null,
        taskCode: null,
        taskName: null,
        address: null,
        discoveryTime: null,
        taskImage: null,
        rectificationTime: null,
        rectificationImage: null,
        checkTime: null,
        checkImage: null,
        taskStatus: null,
        repairDesc: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRepair(id).then((response) => {
        this.form = response.data;
        // console.log("查看状态");
        // console.log(this.form);
        this.open = true;
        this.title = "修改维修任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRepair(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRepair(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除选中的数据项？")
        .then(function () {
          return delRepair(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/repair/export",
        {
          ...this.queryParams,
        },
        `repair_${new Date().getTime()}.xlsx`
      );
    },
    /** 列是否显示 */
    getColumn(key) {
      const res = this.columns.filter((item) => item.key === key);
      if (res.length >= 1) {
        return res[0].visible;
      } else {
        return false;
      }
    },
    /** 员工管理序号 */
    rowPersonIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 复选框选中数据 */
    handlePersonSelectionChange(selection) {
      this.checkedPerson = selection.map((item) => item.index);
    },
    // 派遣任务
    Taskdispatch(row) {
      // 判断状态是否是已经整改
      if (row.taskStatus != 0) {
        this.$modal.msgError("该工单已整改，不能再进行派遣");
        return;
      }
      this.reset();
      const id = row.id || this.ids;
      getRepair(id).then((response) => {
        this.form = response.data;
        //  打开派遣页面
        this.openTask = true;
        this.getRepairPersonList();
      });
    },
    // 添加员工
    handleAddPerson() {
      let obj = {};
      obj.id = "";
      obj.personPhon = "";
      obj.certificateId = "";
      obj.teamId = "";
      obj.postId = "";
      this.personList.push(obj);
      // console.log("personList:", this.personList);
    },
    // 删除添加的员工
    handleDeletePerson() {
      if (this.checkedPerson.length == 0) {
        this.$modal.msgError("请先选择要删除的员工数据");
      } else {
        const RepairPerson = this.personList;
        const checkedPersons = this.checkedPerson;
        this.personList = RepairPerson.filter(function (item) {
          return checkedPersons.indexOf(item.index) == -1;
        });
      }
    },
    // 补充员工信息
    fillPersonInfo(index, id) {
      const slelectPerson = this.repairPersonList.find(
        (item) => item.id === id
      );
      // console.log("选择的员工：", slelectPerson);
      if (slelectPerson) {
        this.personList[index].personPhone = slelectPerson.personPhone;
        this.personList[index].certificateId = slelectPerson.certificateId;
        this.personList[index].teamId = slelectPerson.teamId;
        this.personList[index].postId = slelectPerson.postId;
      }
    },

    // 获取维修部的员工列表
    getRepairPersonList() {
      // 维修部岗位id
      let postId = 3;
      getPostPerson(postId).then((response) => {
        this.repairPersonList = response.data;
        // console.log("repairpersonList:", this.repairPersonList);
      });
    },
    // 关闭派遣任务弹窗
    closeopenTask() {
      this.openTask = false;
      // 清空选择的商品信息
      this.personList = [];
    },
    // 确定派遣员工
    AddTask() {
      // 获取派遣的员工的id， 传参到后端（员工可能有多个）
      // 遍历personList，获取员工id
      let repairIds = [];
      console.log("personList:", this.personList);
      this.personList.forEach((item) => {
        repairIds.push(item.id);
      });
      // console.log("repairIds:", repairIds);
      // 获取当前的维修任务的id，也传到后端
      // console.log("form:", this.form);
      let taskId = this.form.id;
      // 构造一个对象，ids + taskid 传给后端。

      let params = {
        repairIds: repairIds,
        taskId: taskId,
      };

      dispatchTask(params).then((response) => {
        // console.log("response:", response);
        this.$modal.msgSuccess("派遣员工成功");

        this.openTask = false;
        // 清空选择的员工信息
        this.personList = [];
      });
      //  给后端发送一个监控对方信箱的标志，然后定时检查
      // 如果任务还在信箱中且维修状态改变了，则员工已接取该任务
      // 若 对方信箱中没有该任务，则对方已拒绝接取该任务
      // 算了算了，让后端进行定时检查更好，前端换页面，检查就失效了

      // 开启定时任务,检查对对方是否接取任务，获取任务对象
      // 先修改任务对象的调用方法的参数，
      // 获取当前的在线用户id
      console.log("当前用户id:", this.id);
      //修改后便运行了。
      this.updateJob(repairIds, taskId, this.id),
        // 清空 定时任务
        (this.job = {});
    },

    getJob() {
      let jobId = 101;
      getJob(jobId).then((response) => {
        console.log("response:", response);
        this.job = response.data;
      });
    },
    updateJob(ids, taskId, managerId) {
      // @param ids     ids  员工id
      //  * @param taskId  任务id   维修任务id
      //  * @param adminId 管理员id     当前用户id

      // checkMsg.checkRepair('105,8',6L,1L)
      this.job.invokeTarget = `checkMsg.checkRepair('${ids}', ${taskId}L, ${managerId}L)`;

      this.job.status = 0;

      updateJob(this.job).then((response) => {
        console.log("response:", response);
      });
    },
  },
};
</script>
